import {createRouter, createWebHistory} from "vue-router";
import {handleRouterError} from '@/utils/errorHandler.js'
import NProgress from '@/utils/progress.js'  // 引入配置好的 nprogress
import {useUserStore} from '@/stores/pages/user'
import { MENU_PERMISSIONS } from '@/constants/permissions.js'

//路由实例
const router = createRouter({
    history: createWebHistory(),
    //路由规则
    routes: [
        {
            path: '/',
            redirect: '/auth/login'
        },
        {
            path: '/auth',
            component: () => import('@/layouts/LoginLayout.vue'),
            meta: {isPublic: true},
            children: [
                {
                    path: 'login',
                    name: 'login',
                    component: () => import('@/views/Login.vue')
                }
            ]
        },
        {
            path: '/app',
            component: () => import('@/layouts/index.vue'),
            meta: {requiresAuth: true},
            children: [
                {
                    path: 'dashboard',
                    name: 'dashboard',
                    component: () => import('@/views/Dashboard.vue'),
                    meta: {title: '仪表盘', ...MENU_PERMISSIONS.DASHBOARD}
                },
                {
                    path: 'UserManagement',
                    name: 'UserManagement',
                    component: () => import('@/views/PermissionsManagement/UserManagement.vue'),
                    meta: {title: '用户管理', ...MENU_PERMISSIONS.USER_MANAGEMENT}
                },
                {
                    path: 'RoleManagement',
                    name: 'RoleManagement',
                    component: () => import('@/views/PermissionsManagement/RoleManagement.vue'),
                    meta: {title: '角色管理', ...MENU_PERMISSIONS.ROLE_MANAGEMENT}
                },
                {
                    path: 'PersonalSettings',
                    name: 'PersonalSettings',
                    component: () => import('@/views/PersonalCenter/PersonalSettings.vue'),
                    meta: {title: '个人设置', ...MENU_PERMISSIONS.PERSONAL_SETTINGS}
                },
            ]
        },
        {
            path: '/403',
            name: 'forbidden',
            component: () => import('@/views/ExceptionPage/Forbidden.vue'),
            meta: {isPublic: true}
        },
        {
            path: '/500',
            name: 'server-error',
            component: () => import('@/views/ExceptionPage/ServerError.vue'),
            meta: {isPublic: true}
        },
        {
            path: '/:pathMatch(.*)*',
            name: 'not-found',
            component: () => import('@/views/ExceptionPage/NotFound.vue'),
            meta: {isPublic: true}
        }
    ]
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
    // 对于公共路由，直接放行
    if (to.meta.isPublic) {
        NProgress.start();
        next();
        return;
    }

    const authStore = useUserStore();

    // 检查目标路由是否需要认证
    const requiresAuth = !to.meta.isPublic && to.matched.some(route => route.meta.requiresAuth);

    // 如果需要认证但未认证，跳转到登录页
    if (requiresAuth && !authStore.isAuthenticated) {
        next('/auth/login');
        return;
    }

    // 如果已认证，检查角色权限（有token、但角色权限不符合）
    /*
        SUPER_ADMIN（超级管理员）：拥有系统最高权限、可管理所有用户和权限配置、适合系统维护和配置管理
        ADMIN（管理员）：拥有日常管理权限、可管理普通用户和业务数据、限制权限体系修改
        USER（普通用户）：只能访问公开内容、仅具备查询权限，无增删改权限
    */
    if (authStore.isAuthenticated && to.meta.roles) {
        // 获取用户角色
        const userRoles = authStore.getUserRoles();
        // 角色数据验证
        if (!userRoles || !Array.isArray(userRoles)) {
            next('/500');
            return;
        }

        const hasRolePermission = to.meta.roles.some(role => userRoles.includes(role));
        if (!hasRolePermission) {
            next('/403');
            return;
        }
    }

    // 检查细粒度权限
    if (to.meta.permission) {
        // 检查用户是否具有该权限
        const hasPermission = authStore.hasPermission(to.meta.permission);
        // 如果该用户没有权限，跳转到无权限页面
        if (!hasPermission) {
            next('/403');
            return;
        }
    }

    //开始进度条
    NProgress.start();
    next();
})

// 全局后置守卫(1)
router.afterEach(() => {
    //结束进度条
    NProgress.done();
})

// 路由错误处理
router.onError((error) => {
    NProgress.done(); // 确保出错时也关闭
    handleRouterError(error, router.currentRoute.value);

    // 如果是模块加载失败，可以尝试重新加载页面
    if (error.name === 'ChunkLoadError') {
        window.location.reload();
    }
})

//导出路由器实例，以便在main.js中使用
export default router